package fm.yichenet.service.impl;

import fm.dao.HibernateBaseDao;
import fm.entity.AccountBalance;
import fm.entity.CashApplication;
import fm.entityEnum.CrashStatusEnum;
import fm.exception.BizException;
import fm.web.CurrentRequest;
import fm.yichenet.service.AccountBalanceService;
import fm.yichenet.service.CashApplicationService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

/**
 * 提现申请业务层代码
 * Created by CM on 2017/6/28.
 */
@Service
public class CashApplicationServiceImpl implements CashApplicationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CashApplicationService.class);
    @Autowired
    AccountBalanceService accountBalanceService;
    @Autowired
    HibernateBaseDao baseDao;

    @Override
    public List<CashApplication> getUserCashApplications(String userId, String startTime, String endTime, CrashStatusEnum status, Integer pageNum, Integer pageSize) {
        String hql = "from CashApplication ca where 1=1 ";
        if (userId != null) {
            hql += "and ca.wxUserId=" + userId;
        }
        if (StringUtils.isNotEmpty(startTime)) {
            hql += " and Date(ca.applicationTime) >= str_to_date('" + startTime + "','yyyy-MM-dd HH:mm:ss')";

        }
        if (StringUtils.isNotEmpty(endTime)) {
            hql += " and Date(ca.applicationTime) <= str_to_date('" + endTime + "','yyyy-MM-dd HH:mm:ss')";
        }

        if (status != null) {
            hql += " and ca.status =?";
        }

        hql += " order by applicationTime desc ";
        if (status != null) {
            return (List<CashApplication>) baseDao.pageQuery(hql, pageNum, pageSize, status);
        }

        return (List<CashApplication>) baseDao.pageQuery(hql, pageNum, pageSize);
    }

    @Override
    public long countUserCashApplications(String userId, String startTime, String endTime, CrashStatusEnum status) {
        String hql = "select count(ca.id) from CashApplication ca where 1=1 ";
        if (userId != null) {
            hql += "and ca.wxUserId=" + userId;
        }
        if (StringUtils.isNotEmpty(startTime)) {
            hql += " and Date(ca.applicationTime) >= str_to_date('" + startTime + "','yyyy-MM-dd HH:mm:ss')";

        }
        if (StringUtils.isNotEmpty(endTime)) {
            hql += " and Date(ca.applicationTime) <= str_to_date('" + endTime + "','yyyy-MM-dd HH:mm:ss')";
        }

        if (status != null) {
            hql += " and ca.status =?";
        }

        hql += " order by applicationTime desc ";
        if (status != null) {
            return baseDao.count(hql, status);
        }
        long count = baseDao.count(hql);
        return count;
    }

    @Override
    public CashApplication getById(Long id) {
        return (CashApplication) baseDao.getById(CashApplication.class, id);
    }

    @Override
    public CashApplication update(CashApplication application) {
        baseDao.update(application);
        return application;
    }

    @Override
    public CashApplication add(CashApplication application) throws Exception {
        if (application == null) {
            throw new BizException("参数缺失");
        }
        if (application.getAmount().doubleValue() < 0) {
            throw new BizException("提现金额非法，请填入大于0的金额！");
        }
        application.setWxUserId((String) CurrentRequest.getCurrentUserId());
        AccountBalance ab = accountBalanceService.addOrGetBalance(application.getWxUserId());

        if (ab.getBalance().subtract(application.getAmount()).doubleValue() < 0) {
            throw new BizException("操作失败，您的账户余额不足！");
        }
        application.setApplicationTime(new Timestamp(System.currentTimeMillis()));
        application.setStatus(CrashStatusEnum.WAIT_CHECK);
        LOGGER.info("用户：{}发起提现：￥{}元", application.getWxUserId(), application.getAmount().doubleValue());
        baseDao.add(application);
        return application;
    }

    @Override
    public void applyApplication(Long id, String remark) {
        CashApplication application = getById(id);
        if (application == null) {
            throw new BizException("操作失败，未找到对应的提现申请信息");
        }

        AccountBalance ab = accountBalanceService.addOrGetBalance(application.getWxUserId());
        if (ab == null) {
            throw new BizException("未找到对应的用户信息，操作失败!");
        }
        if (application.getAmount().doubleValue() <= 0) {
            throw new BizException("提现申请金额为负数，属于非法操作！！");
        }

        if (ab.getBalance().subtract(application.getAmount()).doubleValue() <= 0) {
            throw new BizException("用户账户余额不足，操作失败！");
        }

        BigDecimal rest = ab.getBalance().subtract(application.getAmount());

        accountBalanceService.updateBalance(rest, application.getWxUserId(), "提现扣款");
        application.setCheckTime(new Timestamp(System.currentTimeMillis()));
        application.setRemark(remark);
        application.setStatus(CrashStatusEnum.SUCCESS);
        update(application);
    }

    @Override
    public void refuseApplication(Long id, String remark) {
        CashApplication application = getById(id);
        application.setCheckTime(new Timestamp(System.currentTimeMillis()));
        application.setRemark(remark);
        application.setStatus(CrashStatusEnum.FAILED);
        update(application);
    }
}
